package com.example.musicapp

import android.os.Bundle
import android.view.View
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.lifecycle.lifecycleScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import com.google.android.material.tabs.TabLayout
import com.google.android.material.tabs.TabLayoutMediator
import com.example.musicapp.databinding.ActivityMainBinding
import com.bumptech.glide.Glide
import com.bumptech.glide.load.engine.DiskCacheStrategy
import androidx.activity.viewModels
import com.example.musicapp.viewmodel.MusicViewModel
import com.example.musicapp.adapter.MainPagerAdapter
import com.example.musicapp.model.Song
import com.example.musicapp.network.RetrofitClient

class MainActivity : AppCompatActivity() {
    private lateinit var binding: ActivityMainBinding
    private val viewModel: MusicViewModel by viewModels()

    fun switchToPage(position: Int) {
        binding.viewPager.currentItem = position
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)

        ViewCompat.setOnApplyWindowInsetsListener(binding.root) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }

        setupNavigation()
        setupMiniPlayer()
        initializePlaylist()
    }

    private fun setupMiniPlayer() {

        binding.miniPlayer.root.visibility = View.GONE

        viewModel.currentSong.observe(this) { song ->
            binding.miniPlayer.apply {
                root.visibility = View.VISIBLE
                miniTitle.text = song.title
                miniArtist.text = song.artist
                
                Glide.with(this@MainActivity)
                    .load(song.coverUrl)
                    .diskCacheStrategy(DiskCacheStrategy.ALL)
                    .placeholder(android.R.drawable.ic_menu_gallery)
                    .into(miniCover)
            }
        }

        viewModel.isPlaying.observe(this) { isPlaying ->
            binding.miniPlayer.miniPlayPause.setImageResource(
                if (isPlaying) android.R.drawable.ic_media_pause
                else android.R.drawable.ic_media_play
            )
        }

        // 设置点击事件
        binding.miniPlayer.apply {
            root.setOnClickListener {
                binding.viewPager.currentItem = 1  // 切换到播放器页面
            }
            miniPlayPause.setOnClickListener { viewModel.togglePlayPause() }
            miniPrevious.setOnClickListener { viewModel.playPrevious() }
            miniNext.setOnClickListener { viewModel.playNext() }
            miniPlaylist.setOnClickListener {
                binding.viewPager.currentItem = 2  // 切换到播放列表页面
            }
        }
    }

    private fun setupNavigation() {
        binding.viewPager.adapter = MainPagerAdapter(this)

        TabLayoutMediator(binding.navView, binding.viewPager) { tab, position ->
            tab.text = when (position) {
                0 -> "推荐"
                1 -> "播放器"
                2 -> "播放列表"
                else -> ""
            }
        }.attach()
    }

    private fun initializePlaylist() {
        lifecycleScope.launch(Dispatchers.IO) {
            try {
                val playlistResponses = RetrofitClient.musicApi.getPlaylist()
                withContext(Dispatchers.Main) {
                    val songs = playlistResponses.map { response ->
                        Song(
                            id = response.id,
                            title = response.title,
                            artist = response.singer,
                            album = "",
                            coverUrl = response.coverImgUrl,
                            duration = when(response.id) {
                                1 -> 253  // 甜蜜蜜
                                2 -> 224  // 小城故事
                                3 -> 271  // 雨蝶
                                4 -> 242  // 风中的承诺
                                else -> 180
                            }
                        )
                    }
                    viewModel.setPlaylist(songs)
                }
            } catch (e: Exception) {
                withContext(Dispatchers.Main) {
                    android.util.Log.e("MainActivity", "Error initializing playlist", e)
                }
            }
        }
    }
}